package com.hmdp.utils;

import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    //后置
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从线程中移除用户
        UserHolder.removeUser();
    }

    //前置拦截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session获取用户
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        //判断用户是否存在
        if(user == null){
            response.setStatus(401);
            return false;
        }
        //存在则存在ThreadLocal
        UserHolder.saveUser((UserDTO) user);

        //放行
        return true;

    }
}
